package org.example.day12;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 4.2.1 类ReentrantReadWriteLock的使用: 读读共享
 */
public class MyThread4 {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public void read(){
        try {
            //获取读锁
            lock.readLock().lock();
            System.out.println("获得读锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
            System.out.println("释放读锁 " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) {
        MyThread4 m4 = new MyThread4();
        Thread4A ta = new Thread4A(m4);
        ta.setName("A");
        Thread4B tb = new Thread4B(m4);
        tb.setName("B");
        ta.start();
        tb.start();
    }
}

class Thread4A extends Thread{
    private MyThread4 m4;

    public Thread4A(MyThread4 m4) {
        this.m4 = m4;
    }

    @Override
    public void run() {
        m4.read();
    }
}
class Thread4B extends Thread{
    private MyThread4 m4;

    public Thread4B(MyThread4 m4) {
        this.m4 = m4;
    }

    @Override
    public void run() {
        m4.read();
    }
}